package com.jeesite.modules.restful.user;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jeesite.common.bean.response.user.AcUserResponse;
import com.jeesite.common.bean.result.ResultBean;
import com.jeesite.common.bean.result.ResultEnum;
import com.jeesite.common.bean.user.UserLoginBean;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.HttpUtil;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.user.entity.ActivityUser;
import com.jeesite.modules.user.service.ActivityUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;

import static com.jeesite.common.utils.ResultUtil.error;
import static com.jeesite.common.utils.ResultUtil.success;
import static com.jeesite.common.utils.ResultUtil.successBody;

@RestController
@RequestMapping("/interface/activity/user")
public class ActivityUserRestfulController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ActivityUserRestfulController.class);

    private final ActivityUserService service;


    @Autowired
    public ActivityUserRestfulController(ActivityUserService service) {
        this.service = service;
    }

    @Value("${user.login.appid}")
    private String appid;
    @Value("${user.login.secret}")
    private String secret;

    /**
     * 记录用户
     *
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/record/{code}")
    public ResultBean recordUser(@NotBlank(message = "code不能为空") @PathVariable("code") String code) throws Exception {
        logger.info("访问:/record/{}", code);
        String json = HttpUtil.wx_getOpenId2Json(appid, secret, code);
        if (!json.equals("")) {
            if (json.contains("errcode")) {
                return error("请求失败", JSONUtils.parse(json), 1);
            }
            //获得openid
            JsonObject jsonObject = (JsonObject) new JsonParser().parse(json);
            String openid = jsonObject.get("openid").getAsString();
            logger.info("openid:{}", openid);
            //
            ActivityUser oldUser = getUserInfoByOpenid(openid);
            if (oldUser == null) {
                ActivityUser activityUser = new ActivityUser();
                activityUser.setOpenid(openid);
                service.save(activityUser);
            }
            return success("请求成功", JSONUtils.parse(json), 1);
        }
        return error(ResultEnum.ERROR_UNKNOWN);
    }

    /**
     * 登录
     *
     * @param userLoginBean
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public ResultBean login(@RequestBody UserLoginBean userLoginBean) throws Exception {
        logger.info("访问:/record/login");
        ActivityUser user = userLoginBean.getUser();
        String openid = userLoginBean.getOpenid();
        //条件查询用户
        ActivityUser activityUser = getUserInfoByOpenid(openid);
        if (activityUser == null) {//用户不存在
            return error(ResultEnum.LOGIN_ERROR);
        }
        user.setId(activityUser.getId());
        user.setFlag("1");
        //保存or更新
        service.update(user);
        return success("登录成功", new AcUserResponse().doCopier(getUserInfoByOpenid(openid),true), 1);
    }

    /**
     * 更新登录状态
     *
     * @param openid
     * @param state
     */
    @GetMapping("/{openid}/{state}")
    public void setState(@NotBlank(message = "openid不能为空") @PathVariable("openid") String openid, @PathVariable("state") Boolean state) {
        logger.info("访问:/{}/{}", openid, state);
        ActivityUser activityUser = getUserInfoByOpenid(openid);
        if (activityUser != null) {
            activityUser.setFlag(state ? "1" : "0");
            service.save(activityUser);
        }
    }

    /**
     * 获得单个用户
     *
     * @param openid
     * @return
     */
    @GetMapping("/info/{openid}")
    public ResultBean getUserInfo(@NotBlank(message = "openid不能为空") @PathVariable("openid") String openid) {
        logger.info("访问:/info/{}", openid);
        ActivityUser userInfo = getUserInfoByOpenid(openid);
        if (userInfo == null) {
            return error(ResultEnum.USER_ERROR);
        }
        return successBody(new AcUserResponse().doCopier(userInfo, true));
    }


    /**
     * 根据openid获得用户信息
     *
     * @param openid
     * @return
     */
    private ActivityUser getUserInfoByOpenid(String openid) {
        if (StringUtils.isEmpty(openid)) {
            return null;
        }
        ActivityUser query = new ActivityUser();
        query.setOpenid(openid);
        List<ActivityUser> list = service.findList(query);
        return list == null || list.size() == 0 ? null : list.get(0);
    }

    /**
     * 获得所有用户信息
     *
     * @return
     */
    @GetMapping("/info/all")
    public ResultBean getUserInfoAll() {
        List<ActivityUser> list = service.findList(new ActivityUser());
        if (list == null) {
            return error(ResultEnum.USER_ERROR);
        }
        return successBody(new AcUserResponse().doCopiers(list, true));
    }

    @GetMapping("test")
    public ResultBean test() throws Exception {
        return success();
    }

}
